/*
Copyright © 2021 NAME HERE <EMAIL ADDRESS>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main

import (
	"context"
	cli "github.com/urfave/cli/v2"
	"go.uber.org/zap"
	"os"
	"os/signal"
	"platon-tools/go-service/cmd"
	"platon-tools/go-service/go-logger"
	"platon-tools/go-service/module"
	"platon-tools/go-service/module/rpc"
	"platon-tools/go-service/module/web_api"
	"platon-tools/go-service/service"
	"syscall"

	_ "net/http/pprof"
)

func makeServiceConfi(ctx context.Context) (*service.Config, error) {
	/*
		根据参数配置Config
	*/
	return &service.DefaultConfig, nil
}

func appRun(ctx *cli.Context) error {
	sctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	config, err := makeServiceConfi(sctx)

	if err != nil {
		go_logger.Logger.Error("make config failed", zap.Error(err))
		return err
	}

	//go func() {
	//	go_logger.Logger.Sugar().Info(http.ListenAndServe("localhost:9998", nil))
	//}()

	modules := make([]service.Module, 0)
	for _, m := range config.Modules {
		switch m {
		case service.MYSQLTYPE:
			mysql := new(module.MysqlDB)
			modules = append(modules, mysql)
		case service.REDISTYPE:
			redis := new(module.RedisDB)
			modules = append(modules, redis)
		case service.HTTPTYPE:
			httpApi := new(web_api.HttpApi)
			modules = append(modules, httpApi)
		case service.CENTERRPC:
			cRpc := new(rpc.CenterRcp)
			modules = append(modules, cRpc)
		}
	}

	newService := service.NewService(sctx, config)

	newService.RegisterModule(modules...)

	if err := newService.Start(); err != nil {
		go_logger.Logger.Error("start service failed", zap.Error(err))
		return err
	}

	appWait(cancel)

	return newService.Close()
}

func main() {
	//cmd.Execute()
	Commands := append(cmd.Commands, cmd.AuthorityCmd...)
	Commands = append(cmd.Commands, cmd.ConfigCmd...)
	app := &cli.App{
		Name:  "PlatOn Tools",
		Usage: "PlatOn system tool",
		//Version:                version.FormatVersion(),
		Commands:               Commands,
		UseShortOptionHandling: true,
		Action:                 appRun,
	}

	err := app.Run(os.Args)
	if err != nil {
		go_logger.Logger.Error("service running failed", zap.String("service running failed", err.Error()))
	}

}

func appWait(cancelFunc context.CancelFunc) {
	sigs := make(chan os.Signal, 1)
	done := make(chan bool, 1)

	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		sig := <-sigs
		go_logger.Logger.Info(sig.String())
		done <- true
	}()

	go_logger.Logger.Info("waiting signal ...")
	<-done
	go_logger.Logger.Info("app quit ...")
	cancelFunc()
}
